import re
import time
import random
import string

from module.email import Email
from module.github import Github

class Handle:
    "任务处理类"

    # 注册用户名
    user  = None
    # 注册密码
    pwd   = None
    # 注册邮箱
    email = None
    # 注册失败提示
    msg = {
        -1: "申请邮箱失败",
        -2: "注册失败",
        -3: "邮箱激活失败"
    }

    def __init__(self):
        self.user  = self.random()
        self.pwd   = self.random() + "125"
        self.email = self.random() + "@deiie.com"

    # 注册任务
    # 成功         返回  1
    # 申请邮箱失败 返回 -1
    # 注册失败     返回 -2
    # 邮箱激活失败 返回 -3
    def reg(self):

        email = Email()
        if not email.init(self.email):
            return -1

        github = Github()
        if not github.reg(self.user, self.pwd, self.email):
            return -2

        # 检查激活邮件
        i = 0
        while i < 10:
            i += 1
            time.sleep(1)
            arr = email.list()
            for x in arr:
                url = self.geturl(email.get(x[4]))
                if url:
                    break
            else:
                continue
            break

        # 激活邮箱
        if github.active(url):
            return 1
        else:
            return -3

    # 生成随机信息
    def random(self):
        return ''.join(random.sample(string.ascii_lowercase, 8))

    # 获取激活邮件中的激活链接
    def geturl(self, content):
        return re.findall(r'<a class="cta-button" href="(https://github\.com/users/.+?)">Verify email address</a>', content)[0]

    # 把状态码转换为文字提示信息
    def errorMsg(self, status):
        return self.msg[status]

